import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getTimeStamp } from '@/utils/auth'
// create an axios instance
const Timeout = 100000
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 100000 // request timeout
})

//! 检查token的函数，如果当前的时间-当时登录的时间戳 > timeout，那就表示过期了
function checkTime() {
  return Date.now() - getTimeStamp() > Timeout
}
// request interceptor
service.interceptors.request.use(
  (config) => {
    const token = store.getters.token
    if (token) {
      if (checkTime()) {
        //! 如果检查时间到期了，那就退出并且推到登录页面
        store.dispatch('user/logout')
        router.push('/login')
        return Promise.reject('token过期了哦')
      }
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    if (response.error) {
      //! 说明返回的数据失败了
      Message.error(response.error)
      return Promise.reject(response.error)
    }
    return response
  },
  (err) => {
    Message.error(err)
    return Promise.reject(err)
  }
)

export default service
